package com.chenwei.transactional.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;

/**事务工具类
 * @author: chenwei
 * @date: 2021/4/2 22:20
 */
@Component
@Scope("prototype") // 每个事务都是新的实例 目的解决线程安全问题 多例子  这个注解很重要！！！！  有点像给他分配 一个 threadLoad 防止多线程并发
public class CWTransactionalUtils {

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    //开启事务
    public TransactionStatus begin(){
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());
        return transaction;
    }

    //提交事务
    public void commit(TransactionStatus transaction){
        dataSourceTransactionManager.commit(transaction);
    }

    //回滚是事务
    public void rollBack(TransactionStatus transaction){
        dataSourceTransactionManager.rollback(transaction);
    }
}
